﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using elfam.web.Dao;
using elfam.web.Models;
using elfam.web.Services.Results;
using elfam.web.Utils;
using elfam.web.ViewModels;
using Microsoft.Practices.Unity;

namespace elfam.web.Services
{
    public class OrderService
    {
        private IDaoTemplate _daoTemplate;

        [Dependency]
        public IDaoTemplate DaoTemplate
        {
            set { _daoTemplate = value; }
        }

        public AddOrderResult AddOrder(IList<CartItem> items, User user, OrderShippingInfo orderInfo)
        {
            // construct order
            Order order = new Order();
            order.CopyFrom(orderInfo);
            order.User = user;
            order.Discount = user.Discount;
            foreach (CartItem item in items)
            {
                OrderLine line = order.AddOrderLine(item.Product, item.Quantity);

                IList<Income> incomes = FindOldestIncomesForProduct(item.Product, item.Quantity);
                int quantity = item.Quantity;
                foreach (Income income in incomes)
                {
                    int n = Math.Min(quantity, income.QuantityCurrent);
                    income.QuantityCurrent -= n;
                    _daoTemplate.Save(income);
                    Outcome outcome = new Outcome(){Income = income, Quantity = n, SellPrice = item.Product.Price, Discount = order.Discount};
                    quantity -= n;
                    line.AddOutcome(outcome);
                }
            }
            _daoTemplate.Save(order);
            order.Uid = _daoTemplate.FindByID<UniqueId>(order.Id).Uid;
            _daoTemplate.Save(order);

            return new AddOrderResult(){Order = order};
        }

        public void RevertOrder(Order order)
        {
            IEnumerable<Outcome> outcomes = order.Outcomes();
            foreach (Outcome outcome in outcomes)
            {
                outcome.Income.QuantityCurrent += outcome.Quantity;
            }
            order.ClearOutcomes();
            order.Status = OrderStatus.Revoked;
        }

        public IList<Income> FindOldestIncomesForProduct(Product product, int quantity)
        {
            product = _daoTemplate.FindByID<Product>(product.Id);
            List<Income> result = new List<Income>();
            foreach (Income income in product.Incomes.OrderBy(x => x.Date))
            {
                if (income.QuantityCurrent == 0)
                {
                    continue;
                }
                result.Add(income);
                quantity -= Math.Min(income.QuantityCurrent, quantity);
                if (quantity == 0)
                {
                    break;
                }
            }
            if (quantity > 0)
            {
                // not enough products in stock
            }
            return result;
        }

        public void SetStatus(Order order, OrderStatus status)
        {

            if (status == OrderStatus.Payed)
            {
                order.Status = OrderStatus.Payed;
            }
        }

        public void UpdateUserDicount(User user)
        {
            var profit = user.Profit();
            if (profit >= 10000)
            {
                user.Discount = 10;
                _daoTemplate.Save(user);
            }
        }

        public void NotifyUser(Order order, ControllerContext context)
        {
            string message = MailUtils.RenderViewToString("~/Views/MailTemplates/OrderStatusChanged.aspx", order, context);
            MailService.Send("Elfam.ru - Уведомление", message, order.User.Email);
        }


    }
}
